/*
 * @Description: 高级搜索- 操作组件
 * @Author: Rfan
 * @Date: 2022-01-24 11:40:51
 * @LastEditTime: 2023-02-25 19:16:39
 */

import { Button, Col, Row, Space } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAdvanceContext } from '../contexts/AdvanceContext';
import { submitAadvanceSearch } from '@/api/search';
import { updateAdvanceById } from '@/utils/list';
import { useState } from 'react';

const OperateWrap = () => {
  const { dbName, leftCol, scopeList, conditionList, deleteLastConditionItem, clearConditionList } =
    useAdvanceContext();
  const [scope, setScope] = useState([]);
  const navigate = useNavigate();

  /**
   * 删除条件列表最后一项
   */
  const deleteLast: () => void = () => {
    console.log('del');
    deleteLastConditionItem();
  };

  /**
   * 清空条件列表
   */
  const clearConditionListFn = () => {
    clearConditionList();
    // setConditionList([]);
  };

  const submitSearch = () => {
    const todo = scopeList.map((item: any) => item.generateData());
    // TODO:
    const todoList = todo.map((item: any) => ({
      atScopeList: [
        {
          archiveTypeId: item.archiveTypeId,
          atCode: item.atCode,
          atType: item.atType,
          level: item.level
        }
      ],
      fondsId: item.fondsId
    }));
    todoList.map((item: any) => setScope(updateAdvanceById(item.fondsId, item, scope)));
    console.log(scope);
    const condition = conditionList
      .map((item: any) => {
        if (item.type === 1) {
          return item.value;
        }
        return `${item.field}${item.operator}'${item.operand}'`;
      })
      .join(' ');
    const query = {
      pageNo: 1,
      pageSize: 1
    };
    const commonParams = { dbName };
    const param = { condition, scope, commonParams };
    console.log('submit', param, conditionList, commonParams);

    submitAadvanceSearch({ ...query, param }).then((res: any) => {
      const { data } = res;
      navigate('../another-result', {
        state: { data, params: { ...query, param }, type: 3, title: '高级检索' }
      });
    });
  };

  return (
    <div className="operate-wrap">
      <Row gutter={20}>
        <Col className="" span={leftCol}>
          <Space>
            <Button onClick={() => clearConditionListFn()}>清空条件</Button>
            <Button type="primary" onClick={() => deleteLast()}>
              删除末项
            </Button>
          </Space>
        </Col>
        <Col span={24 - leftCol}>
          <Button type="primary" block onClick={() => submitSearch()}>
            组合检索
          </Button>
        </Col>
      </Row>
    </div>
  );
};

export default OperateWrap;
